import { DataSource } from 'typeorm'
import { DataBaseManager } from '../db/DataBaseManager'
import { UserInfo } from '../db/entities/UserInfo'

export class UserInfoService {
  static instance: UserInfoService
  dataSource: DataSource

  constructor(dataSource: DataSource) {
    this.dataSource = dataSource
  }

  static getInstance() {
    return new Promise<UserInfoService>((resolve) => {
      if (!this.instance) {
        DataBaseManager.getMainDataSource().then((dataSource) => {
          this.instance = new UserInfoService(dataSource)
          resolve(this.instance)
        })
      } else {
        resolve(this.instance)
      }
    })
  }

  list(userInfo: UserInfo) {
    let queryBuilder = this.dataSource
      .createQueryBuilder()
      .select('UserInfo')
      .from(UserInfo, 'UserInfo')
    if (userInfo?.userName != null) {
      queryBuilder = queryBuilder.andWhere('UserInfo.userName=:userName', userInfo)
    }
    if (userInfo?.nickName != null) {
      queryBuilder = queryBuilder.andWhere('UserInfo.nickName=:nickName', userInfo)
    }
    const result=queryBuilder.getMany()
    console.log(result)
    return result
  }

  add(userInfo: UserInfo) {
    userInfo.createTime = Date.now().toString()
    userInfo.updateTime = userInfo.createTime
    return this.dataSource.manager.save(this.dataSource.manager.create(UserInfo,userInfo))
  }
}
